package com.uzai.console.service.wechatwork.impl;

import com.uzai.common.enums.GroupSendStatusEnum;
import com.uzai.console.dto.wechatwork.wxworkcontacts.WxworkNewBatchSendMessageTaskDto;
import com.uzai.console.entity.GroupSendJob;
import com.uzai.console.mapper.GroupSendJobMapper;
import com.uzai.console.service.wechatwork.WxworkContactsService;
import com.uzai.console.service.wechatwork.WxworkContactsSyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 企业微信-企业微信通讯录
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class WxworkContactsSyncServiceImpl implements WxworkContactsSyncService {

    Logger logger = LoggerFactory.getLogger(WxworkContactsSyncServiceImpl.class);

    @Autowired
    private WxworkContactsService wxworkContactsService;
    @Autowired
    private GroupSendJobMapper groupSendJobMapper;

    /**
     * 新建群发消息(异步)
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxworkNewBatchSendMessageTaskDto
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void  newBatchSendMessageTaskSync(WxworkNewBatchSendMessageTaskDto wxworkNewBatchSendMessageTaskDto, Long groupSendJobParentId, String loginName){
        //记录发送消息总数
        int sendMsgTotal_real_parent = 0;

        List<Long> deviceUniqueIdList = wxworkNewBatchSendMessageTaskDto.getDeviceUniqueIdList();
        if(deviceUniqueIdList != null && deviceUniqueIdList.size() > 0){
            //循环机器人添加群发子任务
            for(Long deviceUniqueId :  deviceUniqueIdList){
                int sendMsgTotal_real_son = wxworkContactsService.newBatchSendMessageTaskSync(wxworkNewBatchSendMessageTaskDto, groupSendJobParentId, deviceUniqueId, loginName);
                sendMsgTotal_real_parent = sendMsgTotal_real_parent + sendMsgTotal_real_son;
            }
        }

        if(groupSendJobParentId != null){
            GroupSendJob groupSendJob = groupSendJobMapper.selectById(groupSendJobParentId, wxworkNewBatchSendMessageTaskDto.getMerId());
            if(groupSendJob != null){
                //修改主任务状态
                groupSendJob.setStatus(GroupSendStatusEnum.NOT_START.getValue());
                groupSendJob.setTotalCount(sendMsgTotal_real_parent);
                groupSendJobMapper.updateTotalCountById(groupSendJob);

                //批量修改子任务的状态
                groupSendJobMapper.updateStatusByParentId(GroupSendStatusEnum.NOT_START.getValue(), groupSendJobParentId, wxworkNewBatchSendMessageTaskDto.getMerId());
            }
        }
    }

}
